package cn.web.tunnelrobot.service.impl;

import cn.web.tunnelrobot.dao.UserDao;
import cn.web.tunnelrobot.dao.UserRecordDao;
import cn.web.tunnelrobot.dao.WorkAreaDao;
import cn.web.tunnelrobot.dto.UserLoginReturn;
import cn.web.tunnelrobot.pojo.User;
import cn.web.tunnelrobot.pojo.UserRecord;
import cn.web.tunnelrobot.pojo.WorkArea;
import cn.web.tunnelrobot.service.UserService;
import cn.web.tunnelrobot.util.Constants;
import cn.web.tunnelrobot.util.EncryptedUtil;
import cn.web.tunnelrobot.util.EntityUtils;
import cn.web.tunnelrobot.util.SendPhoneCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRecordDao userRecordDao;
    @Autowired
    private WorkAreaDao workAreaDao;

    @Override
    public HashMap<String, Object> getUserInfo(User user, HttpSession session) throws Exception {
        HashMap<String,Object> map = new HashMap<String,Object>();
        User user1 = new User();
        user1.setUsAccount(user.getUsAccount());
        User u = userDao.getUserInfo(user1);
        if(u != null){
            if (!u.getUsRole().equals(user.getUsRole())){
                map.put("code",-1);
                map.put("msg","账号角色不匹配");
                return map;
            }
            if (u.getUsExam() == 0){
                map.put("code",-1);
                map.put("msg","账号审核中");
                return map;
            }else if (u.getUsExam() == 2){
                map.put("code",-1);
                map.put("msg","账号审核未通过");
                return map;
            }else if (EncryptedUtil.validPassword(user.getUsPassword(),u.getUsPassword())){
                session.removeAttribute(Constants.USER_SESSION);
                session.setAttribute(Constants.USER_SESSION, u);
                UserLoginReturn userLoginReturn = EntityUtils.copyObject(u, UserLoginReturn.class);
               /* WorkArea workAreaByUsId = workAreaDao.getWorkAreaByUsId(u.getUsId());
                if (workAreaByUsId != null){
                    userLoginReturn.setPrId(workAreaByUsId.getPrId());
                }*/
                userLoginReturn.setPrId(1);//单项目，目前设置为1//////////////////////////////////////////
                map.put("sessionId", session.getId());
                System.out.println("session:"+session);
                u.setUsPassword(null);
                map.put("data",userLoginReturn);
                map.put("code",0);
            }else {
                map.put("code",-1);
                map.put("msg","密码错误");
                return map;
            }
        }else {
            map.put("code",-1);
            map.put("msg","账号不存在");
            return map;
        }
        return map;
    }

    @Override
    public HashMap<String, Object> register(User user) throws Exception {
        HashMap<String,Object> map = new HashMap<String,Object>();
        if(Constants.is_intranet == 1){
            //内网不提供编辑权限
            map.put("code",-1);
            map.put("msg","内网没有权限");
            return map;
        }
        User user1 = new User();
        user1.setUsAccount(user.getUsAccount());
        User u = userDao.getUserInfo(user1);
        if (u != null){
            if (u.getUsExam() == 2){
                String pwd = EncryptedUtil.getEncryptedPwd(user.getUsPassword());
                u.setUsPassword(pwd);
                u.setUsName(user.getUsName());
                u.setUsIdentity(user.getUsIdentity());
                u.setUsExam(0);
                u.setUsCreateDate(new Date());
                int result = userDao.updateUserInfo(u);
                if (result == 1){
                    map.put("code",0);
                    map.put("msg","注册成功，等待审核");
                }else{
                    map.put("code",-1);
                    map.put("msg","注册失败");
                }
            }else {
                map.put("code",-1);
                map.put("msg","账号已存在");
                return map;
            }
        }else{
            String pwd = EncryptedUtil.getEncryptedPwd(user.getUsPassword());
            user.setUsPassword(pwd);
            user.setUsCreateDate(new Date());
            int result = userDao.addUserInfo(user);
            if (result == 1){
                map.put("code",0);
                map.put("msg","注册成功，等待审核");
            }else{
                map.put("code",-1);
                map.put("msg","注册失败");
            }
        }
        return map;
    }

    @Override
    public HashMap<String, Object> examUser(Integer usId, Integer usExam, String usComment) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        if(Constants.is_intranet == 1){
            //内网不提供编辑权限
            map.put("code",-1);
            map.put("msg","内网没有权限");
            return map;
        }
        User user1 = new User();
        user1.setUsId(usId);
        User user2 = userDao.getUserInfo(user1);
        if (user2.getUsExam() != 0){
            map.put("code",-1);
            map.put("msg","已审核，请勿重复审核");
            return map;
        }
        User user = new User();
        user.setUsId(usId);
        user.setUsExam(usExam);
        user.setUsComment(usComment);
        user.setUsExamDate(new Date());
        int result = userDao.updateUserInfo(user);
        if (result == 1){
            map.put("code",0);
            map.put("msg","审核成功");
           /* HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            User user3 = (User) request.getSession().getAttribute(Constants.USER_SESSION);
            UserRecord userRecord = new UserRecord();
            userRecord.setUsId(user3.getUsId());
            userRecord.setUrOperatContent("审核用户信息");
            userRecord.setUrOperatTime(new Date());
            userRecordDao.addUserRecord(userRecord);*/
        }else{
            map.put("code",-1);
            map.put("msg","审核失败");
        }
        return map;
    }
    @Override
    public HashMap<String, Object> updateUserInfo(String usAccount,String phoneCode,String usPassword,Integer type) {
        HashMap<String,Object> map = new HashMap<String,Object>();
//        if(Constants.is_intranet == 1){
//            //内网不提供编辑权限
//            map.put("code",-1);
//            map.put("msg","内网没有权限");
//            return map;
//        }
        try {
            if(usAccount.length() != 11){
                map.put("code",-1);
                map.put("data","请输入正确的账号!");
                return map;
            }
            User user1 = new User();
            user1.setUsAccount(usAccount);
            User u = userDao.getUserInfo(user1);
            if(u == null){
                map.put("code",-1);
                map.put("data","此账号不存在!");
                return map;
            }else{//用户账号存在,发送验证码
                if(type == 1){//发送验证码
                    SendPhoneCode.send(usAccount);
                    map.put("code",0);
                    map.put("data","验证码发送成功!");
                    return map;
                }else if(type == 2){//修改密码
                    if(usPassword.trim().length()< 6 ){
                        map.put("code",-1);
                        map.put("data","密码长度不能小于6位!");
                        return map;
                    }
                    //判断验证码是否正确
                    if(SendPhoneCode.verPhoneCode.equals(phoneCode.trim())){
                        //判断旧密码与新密码是否一致
                        if (EncryptedUtil.validPassword(usPassword, u.getUsPassword())) {
                            map.put("code", "-1");
                            map.put("data", "新密码不能与旧密码一致,请重新输入!");
                            return map;
                        }else{
                            usPassword = EncryptedUtil.getEncryptedPwd(usPassword.trim());
                            User user2 = new User();
                            user2.setUsId(u.getUsId());
                            user2.setUsPassword(usPassword);
                            int result = 0;
                            result = userDao.updateUserInfo(user2);
                            if(result >0){
                                map.put("code",0);
                                map.put("data","修改成功!");
                            }else{
                                map.put("code",-1);
                                map.put("data","修改失败!");
                            }
                            return map;
                        }
                    }else{
                        map.put("code",-1);
                        map.put("data","您输入的验证码不正确,请重新输入!");
                        return map;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",-1);
            map.put("data","接口调用出错!");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> deleteUserByUsId(Integer usId) {
        HashMap<String,Object> map = new HashMap<String,Object>();
//        if(Constants.is_intranet == 1){
//            //内网不提供编辑权限
//            map.put("code",-1);
//            map.put("msg","内网没有权限");
//            return map;
//        }
        int result =  userDao.deleteUserByUsId(usId);
        if (result > 0){
            map.put("code",0);
            map.put("msg","删除成功!");
        }else {
            map.put("code",-1);
            map.put("msg","删除失败!");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> getUserList(String usName, String usDepartment, String usExam, String usAccount, Integer pageNo, Integer pageSize) {
        HashMap<String,Object> map = new HashMap<String,Object>();
            if(usName==""){
                usName=null;
            }
            if(usExam==""){
                usExam=null;
            }
            if(usAccount==""){
                usAccount=null;
            }
        List<User> list = userDao.getUserList(usName,usDepartment,usExam,usAccount, ((pageNo - 1) * pageSize), pageSize);
        if (list != null) {
            map.put("code", 0);
            map.put("msg", "");
            map.put("count",userDao.getUserCount(usName,usDepartment,usExam,usAccount));
            map.put("data", list);
           /* HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            User user3 = (User) request.getSession().getAttribute(Constants.USER_SESSION);
            UserRecord userRecord = new UserRecord();
            userRecord.setUsId(user3.getUsId());
            userRecord.setUrOperatContent("获取用户列表");
            userRecord.setUrOperatTime(new Date());
            userRecordDao.addUserRecord(userRecord);*/
        } else {
            map.put("code", -1);
            map.put("msg", "查询失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> getUserListNoWorkArea() {
        HashMap<String,Object> map = new HashMap<String,Object>();
        List<User> list = userDao.getUserListNoWorkArea();
        map.put("code",0);
        map.put("data",list);
        return map;
    }

    @Override
    public HashMap<String, Object> getUserInfoByUsId(Integer usId) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        User user = new User();
        user.setUsId(usId);
        User user1 = userDao.getUserInfo(user);
        if (user1 != null){
            map.put("code",0);
            map.put("data",user1);
        }else {
            map.put("code",-1);
            map.put("msg","查询失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> batchExam(Integer[] usId, Integer usExam, String usComment) {
        HashMap<String,Object> map = new HashMap<String,Object>();
//        if(Constants.is_intranet == 1){
//            //内网不提供编辑权限
//            map.put("code",-1);
//            map.put("msg","内网没有权限");
//            return map;
//        }
        List<User> userList = userDao.getBatchSelectByUsId(usId);
        if (userList.size() > 0){
            map.put("code",-1);
            map.put("msg","已存在已审核用户，请重新选择");
        }else if(userDao.batchExam(usId,usExam,usComment)>=1){
            map.put("code",0);
            map.put("msg","审核成功");
        } else{
            map.put("code",-1);
            map.put("msg","审核失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> updateUserInfoById(User user) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        try {
            User user2 = new User();
            user2.setUsId(user.getUsId());
            User user1 = userDao.getUserInfo(user2);
            if(user.getUsPassword().equals(user1.getUsPassword())){
                System.out.println("密码相等");
                user.setUsPassword(null);
            }else{
                String usPassword = EncryptedUtil.getEncryptedPwd(user.getUsPassword().trim());
                user.setUsPassword(usPassword);
            }
            int result = userDao.updateUserInfo(user);
            if(result > 0){
                map.put("code",0);
                map.put("msg","修改成功");
            }else{
                map.put("code",-1);
                map.put("msg","修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public HashMap<String, Object> getUserListExam() {
        HashMap<String,Object> map = new HashMap<String,Object>();
        List<User> list = userDao.getUserListExam();
        map.put("code",0);
        map.put("data",list);
        return map;
    }

    /**
     * gbq
     * */
    @Override
    public HashMap<String,Object>  ControlRoleById(Integer uId,Integer usRole){
        HashMap<String,Object> map=new HashMap<>();
        try {
            User user1=new User();
            user1.setUsId(uId);
            User user=userDao.getUserInfo(user1);
            user.setUsRole(usRole);
            userDao.updateUserInfo(user);
            map.put("code",0);
            map.put("msg","授权成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",0);
            map.put("msg","授权失败");
        }
        return map;
    }

}

